let SpellId;
layui.config({
    version:'1510164124181'
}).use(['form','laydate','laypage','table', 'layer', 'element','upload'],function(){
    form = layui.form;
    layer = layui.layer;
    table = layui.table,
    laydate = layui.laydate;//日期
    upload = layui.upload;//上传
    element = layui.element; //元素操作
    laypage = layui.laypage; //分页
    SpellId=GetQueryString("SpellId");
    TypelistByTypeId(2);
    if(SpellId==null||SpellId==""||SpellId==undefined){
        SpellId=0;
        $('.add').show();
    }else{
        SelectSpellListById();
        $('.update').show();
    }
    selectAllProductInfoByInfoPc();
    //日期时间范围
    laydate.render({
        elem: '#SpellTime'
        , type: 'datetime'
        , range: true
        ,trigger: 'click'
    });
});

//查询所有信息
function SelectSpellListById(){
    $.ajax({
        url: httpurl+"/findSpellEntity",
        cache: false,
        data: {
            "id":SpellId
        },
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        success: function(data) {
            let dataInfo=data.data;
            $("#SpellTime").val(dataInfo.starttime+" - "+dataInfo.endtime);
            $("#waitTime").val(dataInfo.waittime);
            $("#personNum").val(dataInfo.num);
            $("#proname").val(dataInfo.productEntity.title);

            let TitleInfo='<div class="mealLists">' +
                    '<li class="margin_left2b prolist">' +
                    '<label class="check-box">' +
                    '<input type="checkbox" checked="checked" onclick="parentListFun(this)" name="parentList" value="'+dataInfo.productEntity.id+'"/>' +
                    '<span>'+dataInfo.productEntity.title+'</span>' +
                    '</label>' +
                    '</li>';
                let dataList=dataInfo.productEntity.setMealEntities;
                if(dataList!=null){
                    TitleInfo+='<li class="margin_left10b prochild">';
                    for(let a=0;a<dataList.length;a++){
                        TitleInfo+='<span class="meals">' +
                                        '<label class="check-box">' +
                                        `<input type="checkbox" ${dataList[a].select?'checked':''} onclick="childrenListFun(this);" name="childrenList" value="${dataList[a].id}"/>`+
                                        '<span>'+dataList[a].meal+'</span>'+
                                        '</label>'+
                                        '&nbsp;&nbsp;&nbsp;拼单价格：<input type="number" step="1" class="form-control form-boxed width10 spellPrice" value="'+dataList[a].spellPrice+'" step="0.01" placeholder="请输入价格" />' +
                                        '&nbsp;&nbsp;&nbsp;普通价格：<input readonly="readonly" type="number" class="form-control form-boxed width10 newprice" value="'+dataList[a].newprice+'" step="0.01" placeholder="请输入普通价格" /></span>'+
                                    '</span><br/>';
                    }
                    TitleInfo+="</li></div>";
                }
            $("#AllChooseList").html(TitleInfo);
        }
    });
}

function submitInfo() {
    $.ajax({
        url: httpurl+"/ProductListByTypeIdInfo",
        cache: false,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType : 'application/json',
        data: {
            "proIdList":listId.join(",")
        },
        success: function(data) {
            let dataList=data.data;
            let TitleInfo="";
            for(let i=0;i<dataList.length;i++) {
                TitleInfo+='<div class="mealList">' +
                    '<li class="margin_left2b prolist">' +
                    '<label class="check-box">' +
                    '<input type="checkbox" name="parentList" onclick="parentListFun(this);" value="'+dataList[i].id+'"/>' +
                    '<span>'+dataList[i].title+'</span>' +
                    '</label>' +
                    '</li>';
                let dataInfo=dataList[i].setMealEntities;
                if(dataInfo!=null){
                    TitleInfo+='<li class="margin_left10b prochild">';
                    for(let a=0;a<dataInfo.length;a++){
                        TitleInfo+='<span class="meals"><label class="check-box">' +
                            '<input type="checkbox" name="childrenList" onclick="childrenListFun(this);" value="'+dataInfo[a].id+'"/>'+
                            '<span>'+dataInfo[a].meal+'</span>'+
                            '</label>'+
                            '&nbsp;&nbsp;&nbsp;拼单价格：<input type="number" step="1" class="form-control form-boxed width10 spellPrice" value="'+dataInfo[a].newprice+'" step="0.01" placeholder="请输入价格" />' +
                            '&nbsp;&nbsp;&nbsp;普通价格：<input readonly="readonly" type="number" class="form-control form-boxed width10 newprice" value="'+dataInfo[a].newprice+'" step="0.01" placeholder="请输入普通价格" /></span>'+
                            '</span><br/>';
                    }
                    TitleInfo+="</li></div>";
                }
            }
            $("#AllChooseList").html(TitleInfo);
        }
    });
}

//分页
function page(){
    laypage.render({
        elem: 'page' //注意，这里的 test1 是 ID，不用加 # 号
        ,count:pageSize //数据总数，从服务端得到
        ,curr: pageNo //获取起始页 location.hash.replace('#!fenye=', '')
        ,hash: 'fenye' //自定义hash值
        ,layout: ['count', 'prev', 'page', 'next', 'skip']
        ,limit:15
        ,jump: function(obj, first){
            //首次不执行
            if(!first){
                //	  console.log("当前页==="+obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                //	  console.log("每页显示条数==="+obj.limit); //得到每页显示的条数
                pageNo=obj.curr;
                pageSize=obj.limit;
                selectAllProductInfoByInfoPc();
            }
        }
    });
}
function SelectMealInfoByType() {
    let TitleInfo="";
    let type=$("#types option:selected").val();
    $.ajax({
        url: httpurl+"/SelectMealInfoByType",
        cache: false,
        data: {
            "proIdList":listId.join(","),
            "type":type
        },
        success: function(data) {
            if(data.rtnCode==200){
                let dataList=data.data;
                for(let i=0;i<dataList.length;i++) {
                    TitleInfo+='<div class="mealLists">' +
                        '<li class="margin_left2b prolist">' +
                        '<label class="check-box">' +
                        '<input type="checkbox" name="parentList" onclick="parentListFun(this)" value="'+dataList[i].id+'"/>' +
                        '<span>'+dataList[i].title+'</span>' +
                        '</label>' +
                        '</li>';
                    let dataInfo=dataList[i].setMealEntities;
                    if(dataInfo!=null){
                        TitleInfo+='<li class="margin_left10b prochild">';
                        for(let a=0;a<dataInfo.length;a++){
                            TitleInfo+='<span class="meals"><label class="check-box">' +
                                '<input type="checkbox" name="childrenList" onclick="childrenListFun(this);" value="'+dataInfo[a].id+'"/>'+
                                '<span>'+dataInfo[a].meal+'</span>'+
                                '</label>'+
                                '&nbsp;&nbsp;&nbsp;拼单价格：<input type="number" class="form-control form-boxed width10 spellPrice" value="'+dataInfo[a].spellPrice+'" step="0.01" placeholder="请输入拼单价格" /></span>' +
                                '&nbsp;&nbsp;&nbsp;普通价格：<input readonly="readonly" type="number" class="form-control form-boxed width10 newprice" value="'+dataInfo[a].newprice+'" step="0.01" placeholder="请输入普通价格" /></span>'+
                                '<br/>';
                        }
                        TitleInfo+="</li></div>";
                    }
                }
            }
            $("#AllChooseList").html(TitleInfo);
        }
    });
}
function SubmitInfo(){
    let SpellTime = $("#SpellTime").val();//下单时间
    let starttime = SpellTime.split(" - ")[0];
    let endtime = SpellTime.split(" - ")[1];
    let personNum=$("#personNum").val();
    let waittime=$("#waitTime").val();

    if(SpellTime==""){layer.alert("请选择拼单时间!");return false;}
    if(waitTime=="" || waittime==0){layer.alert("请输入等待时间!");return false;}
    if(personNum=="" || personNum==0){layer.alert("请输入几人团!");return false;}


    let mealLists=$("#AllChooseList").find(".prolist");
    let proList="";
    for(let i=0;i<mealLists.length;i++){
        let find1 = $(mealLists[i]).find("input[name=parentList]");
        if(find1.is(":checked")){
            let proval = find1.val();//商品id
            let mealList="";
            let select_list = $(mealLists[i]).parent().find(".prochild .meals");
            for(let a=0;a<select_list.length;a++){
                let find = $(select_list[a]).find("input[name=childrenList]");
                let spellPrice = $(select_list[a]).find(".spellPrice");
                if($(find).is(":checked")) {
                    let mealid= $(find).val();
                    let val= $(spellPrice).val();
                    mealList+='{"mealid":'+mealid+',"val":'+val+'}'+",";
                }
            }
            if (mealList.length > 0) {
                mealList = mealList.substring(0, mealList.length - 1);
            }
            proList+='{"nameId":'+proval+',"meal":['+mealList+']},';
        }

    }
    if(proList==""){
        layer.alert("请选择拼单商品!");return false;
    }
    proList=proList.substring(0,proList.length-1);
    let proIdList="["+proList+"]";
    console.log(proList);
    let alertcom='是否确认提交?如果存在设置拼单的商品,此次提交将覆盖之前拼单商品的设置，是否继续？';

    top.layer.confirm(alertcom,{icon: 3,title:'提示信息'},function(index){
        // var index = top.layer.msg('提交中，请稍候',{icon: 16,time:false,shade:0.8});
        let HttpAjax="/updateSpellInfo";
        if(SpellId==0){
            HttpAjax="/insertSpellInfo";
        }
        layer.closeAll();
        setTimeout(function(){
            $.ajax({
                type:"POST",
                url: httpurl+HttpAjax,
                cache: false,
                data: JSON.stringify({
                    "id":SpellId,
                    "proIdList":proIdList,
                    "waittime":waittime,
                    "personNum":personNum,
                    "startTime":starttime,
                    "endTime":endtime,
                }),
                contentType : 'application/json',
                headers: {
                    "Access-Control-Allow-Origin": "*",
                    "Access-Control-Allow-Methods": "*",
                    "Access-Control-Allow-Headers": "Authorization",
                    "Authorization": GetTokenInfo()
                },
                success: function(data) {
                    layer.closeAll();
                    top.layer.msg(data.msg);
                    re();
                    console.log('success');

                },
                error:function(data){
                    layer.closeAll();
                    top.layer.msg('服务器错误')
                    console.log('error');
                }
            });
        },1000);
    });
}
function re() {
    window.location.href="SpellList.html";
}
